﻿using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using ThridGroup.ERP.DTO;
using ThridGroup.ERP.DTO.JobGradeManagementDTO;
using ThridGroup.ERP.RBAC;
using Volo.Abp.AspNetCore.Mvc;
using static Volo.Abp.Identity.IdentityPermissions;

namespace ThridGroup.ERP.Web.Controllers
{
    /// <summary>
    /// 角色管理控制器
    /// </summary>
    public class RBACController : AbpController
    {
        private readonly IRoleServicers _roleServices;
        private readonly IPermissionServices _permissionServices;
        private readonly IUserRoleServices _userRolesServices;
        private readonly UserIServices _userIServices;
        public RBACController(IRoleServicers roleServices, UserIServices userIServices, IPermissionServices permissionServices, IUserRoleServices userRolesServices)
        {
            _roleServices = roleServices;
            _userIServices = userIServices;
            _permissionServices = permissionServices;
            _userRolesServices = userRolesServices;
        }

        #region 角色相关
        /// <summary>
        /// 角色管理
        /// </summary>
        public IActionResult RoleView()
        {
            return View();
        }

        /// <summary>
        /// 添加角色
        /// </summary>
        /// <param name="createRoleDto">角色信息</param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> AddRole([FromBody] CreateRoleDto createRoleDto)
        {
            var result = await _roleServices.AddRole(createRoleDto);
            return Json(new { success = result > 0, message = result > 0 ? "添加成功" : "添加失败" });
        }

        /// <summary>
        /// 查询所有角色
        /// </summary>
        /// <returns></returns>

        [HttpGet]
        public async Task<IActionResult> QueryRole()
        {
            var roles = await _roleServices.QueryRole();
            return Json(new
            {
                code = 0,
                msg = "",
                count = roles.Count,
                data = roles
            });
        }

        [HttpGet]
        /// <summary>
        ///显示角色信息  分页
        /// </summary>
        /// <param name="page"></param>
        /// <param name="limit"></param>
        /// <returns></returns>
        public async Task<IActionResult> GetRole(int page = 1, int limit = 10)
        {

            var roles = await _roleServices.GetRole(page, limit);
            var rolePge = roles.OrderByDescending(a => a.Id).Skip((page - 1) * limit).Take(limit).ToList();

            return Json(new
            {
                code = 0,
                msg = "",
                count = roles.Count, // 如果有分页，这里应为总条数
                data = rolePge
            });

        }

        /// <summary>
        /// 删除角色
        /// </summary>
        /// <param name="id">角色ID</param>
        /// <returns></returns>
        [HttpDelete]
        public async Task<IActionResult> DelRole(int id)
        {
            await _roleServices.DelRole(id);
            return Json(new { success = true, message = "删除成功" });
        }

        /// <summary>
        /// 获取角色详情
        /// </summary>
        /// <param name="id">角色ID</param>
        /// <returns></returns>
        [HttpGet]
        public async Task<IActionResult> FullRole(int id)
        {
            var role = await _roleServices.FullRole(id);
            return Json(new { success = true, data = role });
        }

        /// <summary>
        /// 修改角色信息
        /// </summary>
        /// <param name="createRoleDto">角色信息</param>
        /// <returns></returns>
        [HttpPut]
        public async Task<IActionResult> UpRole([FromBody] CreateRoleDto createRoleDto)
        {
            var result = await _roleServices.UpRole(createRoleDto);
            return Json(new { success = result > 0, message = result > 0 ? "修改成功" : "修改失败" });
        }
        #endregion

        /////////////////////////////========权限管理==========///////////////////////////////

        #region
        /// <summary>
        /// 权限管理视图
        /// </summary>
        /// <returns>视图内容</returns>
        public IActionResult PermissionView()
        {
            return View();
        }
        
        /// <summary>
        /// 添加权限     ---tsh
        /// </summary>
        /// <param name="permission">实体</param>
        /// <returns>受影响行数</returns>
        [HttpPost]
        public async Task<int> AddPermission(Permission permission)
        {
            return  await _permissionServices.AddPermission(permission);
        }

        /// <summary>
        /// 删除权限     ---tsh
        /// </summary>
        /// <param name="id">编号</param>
        /// <returns>受影响行数</returns>
        [HttpDelete]
        public async Task<int> DelPermission(Permission permission)
        {
            return await _permissionServices.DelPermission(permission);
        }

        /// <summary>
        /// 修改权限    ---tsh
        /// </summary>
        /// <param name="permission">实体</param>
        /// <returns>受影响行数</returns>
        [HttpPut]
        public async Task<int> UpdPermission(Permission permission)
        {
            return  await _permissionServices.UpdPermission(permission);
        }

        /// <summary>
        /// 查询权限     ---tsh
        /// </summary>
        /// <returns>集合</returns>
        [HttpGet]
        public IQueryable<Permission> QueryPermission()
        {
           return  _permissionServices.QueryPermission();
        }

        /// <summary>
        /// 保存权限（添加或修改） ---tsh
        /// </summary>
        /// <param name="permission">权限实体</param>
        /// <returns>操作结果</returns>
        [HttpPost]
        public async Task<IActionResult> SavePermission([FromBody] Permission permission)
        {
            try
            {
                int result;
                string message;

                // 根据ID判断是添加还是修改
                if (permission.Id > 0)
                {
                    // 修改权限
                    result = await UpdPermission(permission);
                    message = result > 0 ? "修改成功" : "修改失败";
                }
                else
                {
                    // 添加权限
                    result = await AddPermission(permission);
                    message = result > 0 ? "添加成功" : "添加失败";
                }

                return Json(new { success = result > 0, message = message, data = permission.Id });
            }
            catch (Exception ex)
            {
                return Json(new { success = false, message = ex.Message });
            }
        }

        /// <summary>
        /// 获取权限树形数据
        /// </summary>
        /// <returns>权限树形结构</returns>
        [HttpGet]
        public async Task<IActionResult> GetPermissionTree()
        {
            try
            {
                // 添加日志记录
                Console.WriteLine("开始获取权限树数据");
                
                var tree = await _permissionServices.GetPermissionTree();
                
                Console.WriteLine($"获取到权限树节点数量: {tree?.Count ?? 0}");
                
                return Json(new { success = true, data = tree ?? new List<PermissionTreeDto>() });
            }
            catch (Exception ex)
            {
                Console.WriteLine($"获取权限树出错: {ex.Message}");
                Console.WriteLine($"堆栈跟踪: {ex.StackTrace}");
                
                return Json(new { success = false, message = $"获取权限树失败: {ex.Message}" });
            }
        }

        /// <summary>
        /// 根据ID获取权限详情
        /// </summary>
        /// <param name="id">权限ID</param>
        /// <returns>权限详情</returns>
        [HttpGet]
        public async Task<IActionResult> GetPermissionById(int id)
        {
            try
            {
                var permission = await _permissionServices.GetPermissionById(id);
                if (permission == null)
                {
                    return Json(new { success = false, message = "权限不存在" });
                }
                return Json(new { success = true, data = permission });
            }
            catch (Exception ex)
            {
                return Json(new { success = false, message = ex.Message });
            }
        }

        /// <summary>
        /// 根据ID获取权限详细信息（用于表单回填）
        /// </summary>
        /// <param name="id">权限ID</param>
        /// <returns>权限详细信息</returns>
        [HttpGet]
        public async Task<IActionResult> GetPermissionDetailById(int id)
        {
            try
            {
                Console.WriteLine($"开始获取权限详细信息，ID: {id}");
                
                var permissionDetail = await _permissionServices.GetPermissionDetailById(id);
                if (permissionDetail == null)
                {
                    Console.WriteLine($"权限不存在，ID: {id}");
                    return Json(new { success = false, message = "权限不存在或已被删除" });
                }

                Console.WriteLine($"成功获取权限详细信息: {permissionDetail.PermissionName}");
                return Json(new { 
                    success = true, 
                    data = permissionDetail,
                    message = "获取权限详细信息成功" 
                });
            }
            catch (Exception ex)
            {
                Console.WriteLine($"获取权限详细信息出错: {ex.Message}");
                Console.WriteLine($"堆栈跟踪: {ex.StackTrace}");
                return Json(new { 
                    success = false, 
                    message = $"获取权限详细信息失败: {ex.Message}" 
                });
            }
        }

        /// <summary>
        /// 获取所有权限列表
        /// </summary>
        /// <returns>权限列表</returns>
        [HttpGet]
        public async Task<IActionResult> GetAllPermissions()
        {
            try
            {
                var permissions = await _permissionServices.GetAllPermissions();
                return Json(new { 
                    code = 0,
                    msg = "",
                    count = permissions.Count,
                    data = permissions 
                });
            }
            catch (Exception ex)
            {
                return Json(new { 
                    code = 500,
                    msg = ex.Message,
                    count = 0,
                    data = new List<Permission>() 
                });
            }
        }

        /// <summary>
        /// 初始化测试权限数据
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> InitTestPermissions()
        {
            try
            {
                // 检查是否已经有权限数据
                var existingPermissions = await _permissionServices.GetAllPermissions();
                if (existingPermissions.Count > 0)
                {
                    return Json(new { success = true, message = "权限数据已存在，无需初始化", count = existingPermissions.Count });
                }

                int successCount = 0;

                // 第一步：创建根级权限
                var rootPermissions = new List<Permission>
                {
                    new Permission { PermissionName = "系统管理", FatherPermissionId = 0, PermissionPath = "/system", OrderId = 1, PermissionImg = "layui-icon-set", PermissionState = true },
                    new Permission { PermissionName = "生产系统", FatherPermissionId = 0, PermissionPath = "/production", OrderId = 2, PermissionImg = "layui-icon-engine", PermissionState = true },
                    new Permission { PermissionName = "人力资源", FatherPermissionId = 0, PermissionPath = "/hr", OrderId = 3, PermissionImg = "layui-icon-user", PermissionState = true }
                };

                var rootIds = new Dictionary<string, int>();

                foreach (var permission in rootPermissions)
                {
                    var result = await _permissionServices.AddPermission(permission);
                    if (result > 0)
                    {
                        successCount++;
                        // 获取刚插入的权限ID
                        var insertedPermission = (await _permissionServices.GetAllPermissions())
                            .Where(p => p.PermissionName == permission.PermissionName && p.FatherPermissionId == 0)
                            .FirstOrDefault();
                        if (insertedPermission != null)
                        {
                            rootIds[permission.PermissionName] = insertedPermission.Id;
                        }
                    }
                }

                // 第二步：创建子级权限
                if (rootIds.ContainsKey("系统管理"))
                {
                    var systemId = rootIds["系统管理"];
                    var systemChildren = new List<Permission>
                    {
                        new Permission { PermissionName = "用户管理", FatherPermissionId = systemId, PermissionPath = "/system/user", OrderId = 1, PermissionImg = "layui-icon-user", PermissionState = true },
                        new Permission { PermissionName = "角色管理", FatherPermissionId = systemId, PermissionPath = "/system/role", OrderId = 2, PermissionImg = "layui-icon-group", PermissionState = true },
                        new Permission { PermissionName = "权限管理", FatherPermissionId = systemId, PermissionPath = "/system/permission", OrderId = 3, PermissionImg = "layui-icon-key", PermissionState = true }
                    };

                    foreach (var permission in systemChildren)
                    {
                        var result = await _permissionServices.AddPermission(permission);
                        if (result > 0) successCount++;
                    }
                }

                if (rootIds.ContainsKey("生产系统"))
                {
                    var productionId = rootIds["生产系统"];
                    var productionChildren = new List<Permission>
                    {
                        new Permission { PermissionName = "物料管理", FatherPermissionId = productionId, PermissionPath = "/production/material", OrderId = 1, PermissionImg = "layui-icon-component", PermissionState = true },
                        new Permission { PermissionName = "客户管理", FatherPermissionId = productionId, PermissionPath = "/production/customer", OrderId = 2, PermissionImg = "layui-icon-friends", PermissionState = true }
                    };

                    foreach (var permission in productionChildren)
                    {
                        var result = await _permissionServices.AddPermission(permission);
                        if (result > 0) successCount++;
                    }
                }

                if (rootIds.ContainsKey("人力资源"))
                {
                    var hrId = rootIds["人力资源"];
                    var hrChildren = new List<Permission>
                    {
                        new Permission { PermissionName = "员工管理", FatherPermissionId = hrId, PermissionPath = "/hr/employee", OrderId = 1, PermissionImg = "layui-icon-username", PermissionState = true },
                        new Permission { PermissionName = "薪资管理", FatherPermissionId = hrId, PermissionPath = "/hr/salary", OrderId = 2, PermissionImg = "layui-icon-rmb", PermissionState = true }
                    };

                    foreach (var permission in hrChildren)
                    {
                        var result = await _permissionServices.AddPermission(permission);
                        if (result > 0) successCount++;
                    }
                }

                return Json(new { 
                    success = true, 
                    message = $"成功初始化 {successCount} 条权限数据", 
                    success_count = successCount 
                });
            }
            catch (Exception ex)
            {
                Console.WriteLine($"初始化权限数据出错: {ex.Message}");
                Console.WriteLine($"堆栈跟踪: {ex.StackTrace}");
                return Json(new { success = false, message = $"初始化权限数据失败: {ex.Message}" });
            }
        }

        /// 添加用户
        /// </summary>
        /// <param name="user">用户信息</param>
        /// <returns>返回值</returns>
        [HttpPost]
        public async Task<IActionResult> AddUser([FromBody] UserDTO user)
        {
            var result = await _userIServices.AddUser(user);
            return Json(new { success = result > 0, message = result > 0 ? "添加成功" : "添加失败" });
        }

        /// <summary>
        /// 显示用户信息
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public async Task<JsonResult> ShowUser([FromQuery]ShowUserDTO showUserDTO)
        {
            var user = await _userIServices.ShowUser(showUserDTO);
            var result = user.OrderByDescending(m => m.Id).Skip((showUserDTO.PageIndex - 1) * showUserDTO.PageSize).Take(showUserDTO.PageSize).ToList();
            return Json(new
            {

                code = 0,
                msg = "",
                count = user.Count,
                data = result
            });
        }

        /// <summary>
        /// 删除用户
        /// </summary>
        /// <param name="userId"></param>
        /// <returns></returns>
        [HttpDelete]
        public async Task<IActionResult> DeleteUser(int userId)
        {
            var result = await _userIServices.DeleteUser(userId);
            return Json(new
            {
                success =true,
                message ="删除成功"
            });
        }

        /// <summary>
        /// 获取用户信息
        /// </summary>
        /// <param name="userId"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<IActionResult> GetUser(int userId)
        {
            var result = await _userIServices.GetUser(userId);
            return Json(new { success = true, data = result });
        }

        /// <summary>
        /// 修改用户信息
        /// </summary>
        /// <param name="user"></param>
        /// <returns></returns>
        [HttpPut]
        public async Task<IActionResult> UpdateUser([FromBody] UserDTO user) 
        {
        var result= await _userIServices.UpdateUser(user);
            return Json(new
            {
                success = result > 0,
                message = result > 0 ? "修改成功" : "修改失败"
            });
        }


        #endregion

        #region 用户相关

        /// <summary>
        /// 用户管理
        /// </summary>
        public IActionResult UserView()
        {
            return View();
        }
        /// <summary>
        /// 为用户分配角色
        /// </summary>
        /// <param name="userRoleDto">用户角色信息</param>
        /// <returns>操作结果</returns>
        [HttpPost]
        public async Task<IActionResult> AddUserRole([FromBody] UserRoleDto userRoleDto)
        {
            try
            {
                if (!ModelState.IsValid)
                {
                    return BadRequest(new { 
                        success = false, 
                        message = "请求数据验证失败",
                        errors = ModelState.Values
                            .SelectMany(v => v.Errors)
                            .Select(e => e.ErrorMessage)
                    });
                }

                var result = await _userRolesServices.AddUserRole(userRoleDto);
                return Json(new { 
                    success = true, 
                    data = result,
                    message = "角色分配成功"
                });
            }
            catch (Exception ex)
            {
                return BadRequest(new { 
                    success = false, 
                    message = ex.Message 
                });
            }
        }

        /// <summary>
        /// 获取用户的角色信息
        /// </summary>
        /// <param name="userId">用户ID</param>
        /// <returns>用户角色信息</returns>
        [HttpGet]
        public async Task<IActionResult> GetUserRoles(int userId)
        {
            try
            {
                var result = await _userRolesServices.GetUserRoles(userId);
                return Json(new { 
                    success = true, 
                    data = result 
                });
            }
            catch (Exception ex)
            {
                return BadRequest(new { 
                    success = false, 
                    message = ex.Message 
                });
            }
        }

        /// <summary>
        /// 获取所有用户角色关系
        /// </summary>
        /// <returns>用户角色列表</returns>
        [HttpGet]
        public async Task<IActionResult> QueryUserRole()
        {
            try
            {
                var result = await _userRolesServices.QueryUserRole();
                return Json(new
                {
                    success = true,
                    data = result
                });
            }
            catch (Exception ex)
            {
                return BadRequest(new { 
                    success = false, 
                    message = ex.Message 
                });
            }
        }

        /// <summary>
        /// 获取用户完整角色信息
        /// </summary>
        /// <param name="id">用户ID</param>
        /// <returns>用户角色信息</returns>
        [HttpGet]
        public async Task<IActionResult> FullUserRole(int id)
        {
            try
            {
                var userRole = await _userRolesServices.FullUserRole(id);
                return Json(new { code = 0, data = userRole });
            }
            catch (Exception ex)
            {
                return Json(new { code = 500, msg = ex.Message });
            }
        }
        #endregion
    }

}